<?php

namespace app\api\controller;

use app\common\controller\Api;

use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;

/**
 * 首页接口
 */
class Pay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function getChargeOptions()
    {
        $user = $this->auth->getUser();
        if (in_array($user->group_id, [2, 3])) {
            $options = [];
        } else {
            $options = model('recharge_setting')->order('num', 'asc')->select();
        }
        $this->success('ok', $options);
    }

    public function payToUser()
    {
        $merchantId = '1522447861';

        // 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
        $merchantPrivateKeyFilePath = 'file:///' . realpath(APP_PATH  . '/cert/apiclient_key.pem');
        $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);

        // 「商户API证书」的「证书序列号」
        $merchantCertificateSerial = '177471103C6A6D261032DC2E6A843CE697CAA112';

        // 从本地文件中加载「微信支付平台证书」，可由内置CLI工具下载到，用来验证微信支付应答的签名
        $platformCertificateFilePath  = 'file:///' . APP_PATH . '/cert/wechatpay_591453BF2795775A99989117B951FDBA5C9E9535.pem';
        $onePlatformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);

        // 「微信支付平台证书」的「平台证书序列号」
        $platformCertificateSerial = '591453BF2795775A99989117B951FDBA5C9E9535';

        // 从本地文件中加载「微信支付公钥」，用来验证微信支付应答的签名
        $platformPublicKeyFilePath    = 'file:///' . APP_PATH . '/cert/pub_key.pem';


        $twoPlatformPublicKeyInstance = Rsa::from($platformPublicKeyFilePath, Rsa::KEY_TYPE_PUBLIC);


        // 「微信支付公钥」的「微信支付公钥ID」
        $platformPublicKeyId = 'PUB_KEY_ID_0115224478612025051400291939000001';

        // 构造一个 APIv3 客户端实例
        $instance = Builder::factory([
            'mchid'      => $merchantId,
            'serial'     => $merchantCertificateSerial,
            'privateKey' => $merchantPrivateKeyInstance,
            'certs'      => [
                $platformCertificateSerial => $onePlatformPublicKeyInstance,
                $platformPublicKeyId       => $twoPlatformPublicKeyInstance,
            ],
        ]);

        $platformCertificateSerial = '591453BF2795775A99989117B951FDBA5C9E9535';

        // try {
            $resp = $instance
            ->chain('v3/fund-app/mch-transfer/transfer-bills')
            ->post([
                'headers' => [
                    'Wechatpay-Serial' => $platformCertificateSerial,
                ],
                'json' => [
                    'appid' => 'wx9b40cb2f73a3a04e',
                    'out_bill_no' => 'plfk202004201388',
                    'transfer_scene_id' => '1005',
                    'openid' => 'oquaR7arVZXAQiVlkPdD8MwVcRfM',
                    'user_name' => Rsa::encrypt('樊庆', $onePlatformPublicKeyInstance),
                    'transfer_amount' => 200, // 修改为1元（100分）
                    'transfer_remark' => '新会员开通有礼',
                    // 'notify_url' => 'https://wechatpay.yakexi.tech/notify',
                    'user_recv_perception' => '劳务报酬',
                    'transfer_scene_report_infos' => [
                        [
                            'info_type' => '岗位类型',
                            'info_content' => '销售员'
                        ],
                        [
                            'info_type' => '报酬说明',
                            'info_content' => '5月的佣金'
                        ]
                    ]
                ]
            ]);

            $body = $resp->getBody();
            $content = $body->getContents();
            $content = json_decode($content, true);
            $this->success('ok', $content);

        // } catch (\Exception $e) {
        //     // 进行错误处理
        //     echo $e->getMessage(), PHP_EOL;
        //     if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
        //         $r = $e->getResponse();
        //         echo $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL;
        //         echo (string) $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL;
        //     }
        //     echo $e->getTraceAsString(), PHP_EOL;
        // }

    }
}
